package com.example.proto3;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class TestWrite {
    public static void main(String[] args) throws IOException {
        Contacts.Builder contactBuilder=Contacts.newBuilder();

        //读取本地已存在的contact.bin，反序列化出通讯录对象
//        Contacts contacts=Contacts.parseFrom(new FileInputStream("src/main/java/com/example/proto3/contacts.bin"));
//        contactBuilder=contacts.toBuilder();
        try {
            contactBuilder.mergeFrom(new FileInputStream("src/main/java/com/example/proto3/contacts.bin"));
        }catch (FileNotFoundException e){
            System.out.println("contacts.bin not find,create new file");
        }

        //向通讯录新增一个联系人
        contactBuilder.addContacts(addPeopleInfo());

        //序列化通讯录，将结果写入文件夹
        FileOutputStream outputStream=new FileOutputStream("src/main/java/com/example/proto3/contacts.bin");
        contactBuilder.build().writeTo(outputStream);
        outputStream.close();
    }

    private static PeopleInfo addPeopleInfo(){
        PeopleInfo.Builder builder=PeopleInfo.newBuilder();
        Scanner sc=new Scanner(System.in);
        System.out.println("新增联系人");
        System.out.println("请输入联系人姓名：");
        String name=sc.nextLine();
        builder.setName(name);
        System.out.println("请输入联系人年龄：");
        int age=sc.nextInt();
        sc.nextLine();
        builder.setAge(age);

        for (int i = 0;; i++) {
            System.out.println("请输入联系人电话"+(i+1)+"：(输入回车完成电话新增)");
            String number=sc.nextLine();
            if(number.isEmpty()){
                break;
            }
            PeopleInfo.Phone.Builder phoneBiler=PeopleInfo.Phone.newBuilder();
            phoneBiler.setNumber(number);

            System.out.println("请输入电话类型：（1、移动电话   2、固定电话）");
            int type=sc.nextInt();
            sc.nextLine();
            switch (type){
                case 1:
                    phoneBiler.setType(PeopleInfo.Phone.PhoneType.MP);
                    break;
                case 2:
                    phoneBiler.setType(PeopleInfo.Phone.PhoneType.TEL);
                    break;
                default:
                    System.out.println("非法输入");
                    break;
            }

            builder.addPhone(phoneBiler);
        }
        System.out.println("添加联系人结束");
        return builder.build();
    }
}
